package com.uzai.console.service.sysrole.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.sysrole.SysRoleIdDto;
import com.uzai.console.dto.sysrole.SysRoleInfoDto;
import com.uzai.console.dto.sysrole.SysRoleQuery;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserConfigDto;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserQuery;
import com.uzai.console.entity.KefuUser;
import com.uzai.console.entity.SysRole;
import com.uzai.console.jsonvo.sysrole.MessageDataVo;
import com.uzai.console.mapper.KefuUserMapper;
import com.uzai.console.mapper.SysRoleMapper;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.sysrole.SysRoleService;
import com.uzai.console.vo.sysrole.SysRoleInfoVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/***
 * 多多进宝联盟
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private KefuUserMapper kefuUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /**
     * 查询系统角色列表
     *
     * @param sysRoleQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<SysRoleInfoVo> findSysRoleList(SysRoleQuery sysRoleQuery) {
        //新建返回到页面的LIST对象
        List<SysRoleInfoVo> sysRolePageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<SysRole> page = new Page<>();
        sysRoleQuery.convert(page);
        ArrayList<SysRole> sysRoleList = sysRoleMapper.findByList(page, sysRoleQuery);
        if (sysRoleList != null && sysRoleList.size() > 0) {
            for (SysRole sysRole : sysRoleList) {
                SysRoleInfoVo sysRolePageVo = new SysRoleInfoVo();
                BeanUtils.copyProperties(sysRole, sysRolePageVo);
                sysRolePageVoList.add(sysRolePageVo);
            }
        }

        //返回到页面分页对象
        Page<SysRoleInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(sysRolePageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 添加系统角色
     *
     * @param sysRoleInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void addSysRole(SysRoleInfoDto sysRoleInfoDto) {

        if (StringUtils.isBlank(sysRoleInfoDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入角色名称");
        }

        if (StringUtils.isBlank(sysRoleInfoDto.getAuthData())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择该角色的菜单权限");
        }

        SysRole sysRole_name = sysRoleMapper.selectByNameAndMerId(sysRoleInfoDto.getName(), sysRoleInfoDto.getMerId());
        if (sysRole_name != null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "角色名称重复");
        }

        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleInfoDto, sysRole);

        Integer now = DateUtil.getNowTime();
        sysRole.setId(IdWorker.getId());
        sysRole.setCreateTime(now);
        sysRole.setUpdateTime(now);
        sysRole.setMessageData(Tools.getStrEmpty(JSONObject.toJSONString(sysRoleInfoDto.getMessageDataVo())));
        sysRoleMapper.insert(sysRole);
    }

    /**
     * 修改系统角色
     *
     * @param sysRoleInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateSysRole(SysRoleInfoDto sysRoleInfoDto) {
        if (sysRoleInfoDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if (StringUtils.isBlank(sysRoleInfoDto.getAuthData())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择菜单权限");
        }

        SysRole sysRole = sysRoleMapper.selectById(sysRoleInfoDto.getId(), sysRoleInfoDto.getMerId());
        if (sysRole == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该角色不存在");
        }

        //验证新名字是否已经存在
        if (!sysRole.getName().equals(sysRoleInfoDto.getName())) { //表示修改了名称
            //验证新名称是否存在
            SysRole sysRole_name = sysRoleMapper.selectByNameAndMerId(sysRoleInfoDto.getName(), sysRoleInfoDto.getMerId());
            if (sysRole_name != null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "角色名称重复");
            }
        }

        sysRole.setName(sysRoleInfoDto.getName());
        sysRole.setRemark(sysRoleInfoDto.getRemark());
        sysRole.setAuthData(sysRoleInfoDto.getAuthData());
        sysRole.setMessageData(Tools.getStrEmpty(JSONObject.toJSONString(sysRoleInfoDto.getMessageDataVo())));
        Integer now = DateUtil.getNowTime();
        sysRole.setUpdateTime(now);
        sysRoleMapper.updateById(sysRole);

        //更新客服账号发送消息配置
        //查询所有使用该角色的客服账号
        KefuUserQuery kefuUserQuery = new KefuUserQuery();
        kefuUserQuery.setMerId(sysRoleInfoDto.getMerId());
        kefuUserQuery.setRoleId(sysRole.getId());
        List<KefuUser> kefuUserList = kefuUserMapper.findByList(kefuUserQuery);
        if (kefuUserList != null && kefuUserList.size() > 0) {
            for (KefuUser kefuUser : kefuUserList) {
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.KEFU_SEND_MSG_CONFIG.getKey(), kefuUser.getId()), sysRole.getMessageData());

                //发送
                //发送MQ消息
                KefuUserConfigDto kefuUserConfigDto = new KefuUserConfigDto();
                kefuUserConfigDto.setMerId(kefuUser.getMerId());
                kefuUserConfigDto.setCsId(kefuUser.getId());
                kefuUserConfigDto.setType(1);
                noticeMsgPushProducerService.chatappPushConfig(kefuUserConfigDto);
            }
        }
    }

    /**
     * 删除
     *
     * @param sysRoleIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void deleteSysRole(SysRoleIdDto sysRoleIdDto) {
        if (sysRoleIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        SysRole sysRole = sysRoleMapper.selectById(sysRoleIdDto.getId(), sysRoleIdDto.getMerId());
        if (sysRole == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该角色不存在");
        }

        //查询所有使用该角色的客服账号
        KefuUserQuery kefuUserQuery = new KefuUserQuery();
        kefuUserQuery.setMerId(sysRole.getMerId());
        kefuUserQuery.setRoleId(sysRole.getId());
        List<KefuUser> kefuUserList = kefuUserMapper.findByList(kefuUserQuery);
        if (kefuUserList != null && kefuUserList.size() > 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该角色已经有客服账号在使用");
        }

        sysRoleMapper.deleteById(sysRoleIdDto.getId(), sysRoleIdDto.getMerId());
    }

    /**
     * 查询角色详情
     *
     * @param sysRoleIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public SysRoleInfoVo findSysRoleInfo(SysRoleIdDto sysRoleIdDto) {
        if (sysRoleIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        SysRole sysRole = sysRoleMapper.selectById(sysRoleIdDto.getId(), sysRoleIdDto.getMerId());

        if (sysRole == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该角色不存在");
        }

        SysRoleInfoVo sysRoleInfoVo = new SysRoleInfoVo();
        BeanUtils.copyProperties(sysRole, sysRoleInfoVo);

        sysRoleInfoVo.setMessageDataVo(JSONObject.parseObject(sysRole.getMessageData(), MessageDataVo.class));

        return sysRoleInfoVo;
    }

    @Override
    public void setChildAccountRole(String settingJson) {

        List<KefuUser> kefuUsers = kefuUserMapper.selectHasRoleUsers();
        if (ObjectUtils.isEmpty(kefuUsers)) {
            logger.warn("kefu user has role not found");
            return;
        }
        // 拿到所有的角色id
        List<Long> roleIds = kefuUsers.stream().map(KefuUser::getRoleId).filter(Objects::nonNull).distinct().collect(Collectors.toList());

        List<SysRole> roles = sysRoleMapper.selectByIds(roleIds);

        JSONObject newRoleSetting = JSON.parseObject(settingJson);

        for (SysRole role : roles) {

            String authDataJson = role.getAuthData();
            if (StringUtils.isBlank(authDataJson)) {
                continue;
            }
            JSONObject oldRoleSetting;
            // 解析
            try {
                oldRoleSetting = JSON.parseObject(authDataJson);
            } catch (Exception e) {
                logger.error("role auth data parse error, roleId: {}", role.getId());
                continue;
            }

            JSONObject jsonObject = handleJson(newRoleSetting, oldRoleSetting);
            role.setAuthData(jsonObject.toJSONString());
            role.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
            sysRoleMapper.updateById(role);
        }
    }

    public JSONObject handleJson(JSONObject newSetting, JSONObject oldSetting) {
        JSONObject result = new JSONObject();
        // 遍历老的
        for (Map.Entry<String, Object> oldEntry : oldSetting.entrySet()) {

            String key = oldEntry.getKey();

            if (newSetting.containsKey(key)) {
                JSONArray oldValues = JSON.parseArray(oldEntry.getValue().toString());
                // 为空
                if (ObjectUtils.isEmpty(oldValues)) {
                    result.put(key, newSetting.get(key));
                }
                // 不为空
                else {
                    JSONArray newValues = newSetting.getJSONArray(key);
                    if (ObjectUtils.isNotEmpty(newValues)) {
                        for (Object newValItem : newValues) {
                            if (oldValues.contains(newValItem)) {
                                continue;
                            }
                            oldValues.add(newValItem);
                        }
                    }
                    result.put(key, oldValues);
                }
            } else {
                result.put(key, oldEntry.getValue());
            }
        }
        return result;
    }
}
